<?php
/**
 * @package PHPKit.
 * @author: mawenpei
 * @date: 2016/11/24
 * @time: 19:41
 */
namespace HuoKit\JobMan\Queue;

use Pheanstalk\Pheanstalk;

class BeanstalkdQueue implements IQueue
{
    protected $client;

    public function __construct($config)
    {
        $host = isset($config['host']) ? $config['host'] : '127.0.0.1';
        $port = isset($config['port']) ? $config['port'] : 11300;
        $this->client = new Pheanstalk($host,$port);
    }

    public function put($name,$job)
    {
        return $this->client->putInTube($name,json_encode($job));
    }

    public function pop($name)
    {
        $job = $this->client->reserveFromTube($name,2);
        if($job){
            $jobId = $job->getId();
            $jobData = $job->getData();
            $this->client->delete($job);
            return new Job($jobId,json_encode($jobData,true));
        }
        return $job;
    }
}